#!/usr/bin/env python
import argparse
import numpy as np
from astropy.table import Table
from astropy.time import Time
from matplotlib import pyplot as plt


def run(name, output=None):
    with open(name, encoding='gbk') as f:
        lines = f.readlines()[1:]
        tab = Table.read(lines, format='ascii.no_header', delimiter='\t')
        t = [txt.replace('/', '-') for txt in tab['col1']]
        t = Time(t)
        t0 = Time(t[0].iso.split(':')[0] + ':00:00')
        t = (t.mjd - t0.mjd) * 24

        colnames = tab.colnames[1:]
        valid_cols = []
        colnum = []
        for i in range(len(colnames)):
            if np.abs(tab[colnames[i]]).max() > 1e-5:
                valid_cols.append(colnames[i])
                colnum.append(i+1)

        n = len(valid_cols)
        if n == 0:
            raise Exception('no valid temperature data')
        plt.figure(figsize=(6, n*1.5))
        plt.title('start time: {}'.format(t0.iso))
        for i in range(n):
            y = tab[valid_cols[i]]
            plt.subplot(n, 1, i+1)
            plt.plot(t, y, lw=2, color='g')
            if max(y) - min(y) < 2:
                ax = plt.gca()
                ylim = ax.get_ylim()
                plt.ylim([np.mean(ylim) - 1.1, np.mean(ylim) + 1.1])
            plt.grid(True)
            plt.ylabel('chan {}'.format(colnum[i]))
            if i != n-1:
                plt.tick_params(labelbottom=False)
        plt.xlabel('hours from start')
        if output is not None:
            plt.tight_layout()
            plt.savefig(output)
        else:
            plt.show()
        plt.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('name', type=str)
    parser.add_argument('--output', '-o', default=None, type=str,
                        help='output figure name')
    pars = parser.parse_args()
    run(pars.name, output=pars.output)
